package cn.smbms.controller;


import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    @RequestMapping(value = "/list.html")
    public String list(Model model,
                       @RequestParam(value = "pageIndex",required = false,defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize",required = false,defaultValue = "5") Integer pageSize,
                      @RequestParam(value = "queryname",required = false) String username,
                       @RequestParam(value = "queryUserRole",required = false) Integer userRole){

        List<User> userList = userService.list(pageNo,pageSize,username,userRole);
        int totalCount = userService.count(username,userRole); // 总记录数

        int totalPageCount = totalCount / pageSize; //总页数

        if (totalCount % pageSize != 0){ //判断是否有余数
            totalPageCount++;
        }

        List<Role> roleList = roleService.list();

        model.addAttribute("userList",userList);
        model.addAttribute("roleList",roleList);

        model.addAttribute("totalCount",totalCount);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("currentPageNo",pageNo);
        return "userlist";
    }

    @RequestMapping(value = "/add.html")
    public String toAdd(Model model){
        List<Role> roleList = roleService.list();
        model.addAttribute("roleList",roleList);
        return "useradd";
    }

    @RequestMapping(value = "/add.html",method = RequestMethod.POST)
    public String add(User user, HttpServletResponse response, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "attachs",required = false) MultipartFile[] attachs) throws IOException {

        //文件名 证件照
        String idPicFilename = null;
        //文件名 工作照
        String workPicFilename = null;
        //文件上传
        if (null != attachs){
            for (int i=0;i<attachs.length;i++) {
                MultipartFile attach = attachs[i];
                //判断文件大小
                if (attach.getSize()>5000000){
                    request.setAttribute("uploadFileError", " * 上传大小不得超过 5000k");
                    return "useradd";
                }

                //判断文件格式
                if (!(attach.getOriginalFilename().endsWith("jpg") || attach.getOriginalFilename().endsWith("png")
                        || attach.getOriginalFilename().endsWith("jpeg"))){
                    request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                    return "useradd";

                }

                //文件上传到哪里？目标路径
                String path = session.getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
                //目标文件绝对路径
                String filePath = null;
                //证件照
                if (i==0){
                    idPicFilename = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";//"c:aaa.png";
                    filePath = path+File.separator+idPicFilename;
                }

                //工作照
                if (i==1){
                    workPicFilename = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Work.jpg";//"c:aaa.png";
                    filePath = path+File.separator+workPicFilename;
                }

                File targetFile = new File(filePath);

                //判断目标文件是否存在
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                //把文件传输到目标文件
                attach.transferTo(targetFile);
            }

        }

        user.setIdPicPath(idPicFilename);
        user.setWorkPicPath(workPicFilename);

        boolean result = userService.add(user);

        //如果新增失败
        if (! result){
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("<script>alert('添加失败！');history.back();</script>");
            return null;
        }

        return "redirect:/user/list.html";
    }

    @RequestMapping(value = "/view/{uid}",method = RequestMethod.GET)
    public String view(Model model, @PathVariable(value = "uid") Integer id){
        User user = userService.findUserById(id);
        model.addAttribute("user",user);
        return "userview";
    }

    @ResponseBody
    @RequestMapping(value = "/view",method = RequestMethod.GET)
    public Object viewJson(Integer userId){
        User user = userService.findUserById(userId);
        return user;
    }

    @RequestMapping(value = "/update.html",method = RequestMethod.GET)
    public String toUpdate(Model model, @RequestParam(value = "uid") Integer id){
        User user = userService.findUserById(id);
        model.addAttribute("user",user);

        List<Role> roleList = roleService.list();
        model.addAttribute("roleList",roleList);
        return "usermodify";
    }

    @RequestMapping(value = "/update.html",method = RequestMethod.POST)
    public String update(Model model, User user, HttpServletResponse response) throws IOException {

        boolean result = userService.update(user);

        //如果新增失败
        if (! result){
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("<script>alert('修改失败！');history.back();</script>");
            return null;
        }

        return "redirect:/user/list.html";
    }

    @ResponseBody
    @RequestMapping(value = "/ucexist.html")
    public String ucexist(String userCode){
        User user = userService.ucexist(userCode);
        Map<String,Object> map = new HashMap<String, Object>();
        if (user!=null){
            //已存在
            map.put("userCode","exist");
            String strJson = JSON.toJSONString(map);
            // Json字符串 {"id":1,"name":"abc"}  {"userCode":"exist"}
            return strJson;
        }
        map.put("userCode","noexist");
        String strJson = JSON.toJSONString(map);
        return  strJson;
    }
}
